package com.myJava.common.security;

import com.myJava.common.constant.Constant;
import com.myJava.common.exception.CaptchaException;
import com.myJava.util.RedisUtil;
import com.myJava.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 验证码自定义过滤器
 * @author csy
 * 
 * 
 */
@Component
public class CaptchaFilter extends OncePerRequestFilter {

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private LoginFailureHandler loginFailureHandler;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {

        String url=httpServletRequest.getRequestURI();
        if("/login".equals(url)  && httpServletRequest.getMethod().equals("POST")){
            try{
                validate(httpServletRequest);
            }catch (CaptchaException e){
                // 交给 认证失败管理器处理
                loginFailureHandler.onAuthenticationFailure(httpServletRequest,httpServletResponse,e);
            }
        }

        filterChain.doFilter(httpServletRequest,httpServletResponse);
    }

    /**
     * 校验验证码
     * @param httpServletRequest
     */
    private void validate(HttpServletRequest httpServletRequest) {
        String code=httpServletRequest.getParameter("code");
        String key=httpServletRequest.getParameter("uuid");
        if(StringUtil.isEmpty(code) || StringUtil.isEmpty(key)){
            throw new CaptchaException("验证码错误！");
        }
        if(!code.equals(redisUtil.hget(Constant.CAPTCHA_KEY,key))){
            throw new CaptchaException("验证码错误！");
        }
    }
}
